package com.liujit.pay.wx.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.liujit.pay.common.domain.result.PayResult;
import com.liujit.pay.common.enums.RequestMethod;
import com.liujit.pay.wx.domain.result.*;
import com.liujit.pay.wx.enums.PayApi;
import com.liujit.pay.wx.enums.ReturnCode;
import com.liujit.pay.wx.kit.HttpKit;
import com.liujit.pay.wx.kit.WxPayKit;
import com.liujit.pay.wx.properties.PayProperties;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 关闭订单相关接口
 * @author: liujun
 * @create: 2021-02-20 11:40
 */
public class WxCloseOrderApi {

    /**
     * 关单
     *
     * @param outTradeNo 商户订单号
     * @return
     */
    public static PayResult closeOrder(String outTradeNo) {
        // 配置参数
        PayProperties payProperties = PayProperties.getInstance();
        // 请求地址
        String payApi = String.format(PayApi.CLOSE_ORDER.getApi(), outTradeNo);
        // 请求参数
        JSONObject param = new JSONObject();
        param.set("mchid", payProperties.getMchId());
        // 发送请求
        String resp = closeOrder(param.toString(), payApi, payProperties.getMchId(), payProperties.getKeyPath(), payProperties.getSerialNo());
        JSONObject respJson = JSONUtil.parseObj(resp);
        ReturnCode returnCode = ReturnCode.getReturnCode(respJson.getStr("code"));
        if (returnCode != null) {
            return new PayResult(returnCode.getCode(), returnCode.getMessage());
        }
        return new PayResult();
    }

    /**
     * 发送请求
     *
     * @param body     请求参数
     * @param payApi   请求地址
     * @param mchId
     * @param keyPath
     * @param serialNo
     * @return
     */
    private static String closeOrder(String body, String payApi, String mchId, String keyPath, String serialNo) {
        // 获取请求签名
        String authorization = WxPayKit.buildAuthorization(RequestMethod.POST, payApi, mchId, serialNo, keyPath, body);
        // 发送请求
        return HttpKit.post(WxPayKit.getReqUrl(payApi), authorization, serialNo, body);
    }
}
